/*
 * @Author: pengyong
 * @Date: 2021-03-12 20:44:54
 * @LastEditors: pengyong
 * @LastEditTime: 2021-04-18 17:16:13
 * @Description:
 * @FilePath: /kuilong_web_new/Users/pengyong/Desktop/3rd/supplier_app/screens/WorksheetAddScreen.js
 */
import React, {Component} from 'react';
import {
  SafeAreaView,
  FlatList,
  StyleSheet,
  View,
  Text,
  TextInput,
  StatusBar,
  ScrollView,
  KeyboardAvoidingView,
  Image,
  TouchableOpacity,
} from 'react-native';

import {ListItem, Input, Button} from 'react-native-elements';
import ImagePicker from 'react-native-image-picker';
import {Actions} from 'react-native-router-flux';
import DateTimePicker from 'react-native-modal-datetime-picker';

import Loading from '../components/Loading';
import AreaSelect from '../components/AreaSelect';
import {showToast, checkMobile} from '../utils/index';
import DateUtils from '../utils/DateUtils';
import ListEditItem from '../views/ListEditItem';
import Api from '../Api';

export default class WorksheetAddScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      photos: [],
      customer: {}, // 客户名称及地址
      faultDevices: [], // 出错设备
      faultDesc: '', // 故障描述
      reportTime: '',
      reqiureTime: '', // 到场时间
      linker: '',
      cellphone: '',
      notes: '',
      showReportTimePicker: false, // 报修时间
      showRequireTimePicker: false, // 需要到场时间
      country: '',
      province: '',
      city: '',
      county: ''
    };
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    const {customer, faultDevices} = nextProps;
    if (customer) {
      this.setState({customer});
    }
    if (faultDevices) {
      this.setState({faultDevices});
    }
  }

  chooseImage = () => {
    ImagePicker.showImagePicker(
      {
        title: '请选择图片来源',
        takePhotoButtonTitle: '拍照',
        chooseFromLibraryButtonTitle: '从照片库选择',
        cancelButtonTitle: '取消',
        mediaType: 'photo',
        maxWidth: 1000,
        maxHeight: 1000,
        quality: 0.8,
      },
      response => {
        if (response.didCancel) {
          console.log('User cancelled image picker');
        } else if (response.error) {
          console.log('ImagePicker Error: ', response.error);
        } else if (response.customButton) {
          console.log('User tapped custom button: ', response.customButton);
        } else {
          const {uri, type, fileName} = response;
          const file = {
            uri,
            type,
            filename:
              fileName || uri.substring(uri.lastIndexOf('/') + 1, uri.length),
            name: 'file',
          };
          Loading.show('正在上传...');
          Api.uploadPhoto(file).then(data => {
            const {photos} = this.state;
            if (!data.status && !data.errno) {
              photos.push(data.data[0]);
              this.setState({photos});
              Loading.hide();
            }
          });
        }
      },
    );
  };

  handleSubmit = () => {
    const {
      customer,
      faultDevices,
      faultDesc,
      photos,
      reportTime,
      reqiureTime,
      linker,
      cellphone,
      notes,
      country,
      province,
      city,
      county
    } = this.state;
    const {id, customerName, address} = customer;
    if (!reportTime) {
      showToast('请选择报修时间');
      return;
    }
    if (!id || !customerName) {
      showToast('请选择客户');
      return;
    }
    if (!Object.keys(faultDevices).length) {
      showToast('请选择报修设备');
      return;
    }
    if (!faultDesc) {
      showToast('请输入故障描述');
      return;
    }
    if (!linker) {
      showToast('请输入联系人');
      return;
    }
    if (cellphone && !checkMobile(cellphone)) {
      showToast('请输入合法手机号');
      return;
    }
    const formatDevice = Object.values(faultDevices)
      .map(item => item.id)
      .join(',');
    const data = {
      customerId: id,
      customerName,
      address,
      faultDevice: formatDevice,
      faultDesc,
      faultPicture: photos.join(','),
      reportTime,
      reqiureTime,
      linker,
      cellphone,
      notes,
      country,
      province,
      city,
      county
    };
    Loading.show('正在保存...');
    Api.addAccident(data)
      .then(res => {
        Loading.hide();
        if (res && res.id) {
          Loading.hide();
          showToast('保存成功');
          setTimeout(() => {
            Actions.pop();
          }, 500);
        } else {
          showToast(res.message || '保存失败');
        }
      })
      .catch(e => {
        Loading.hide();
      });
  };

  handleChooseDate = date => {
    const time = DateUtils.formatDate('y-m-d h:i:s', date);
    const { showRequireTimePicker, showReportTimePicker } = this.state
    if (showReportTimePicker) {
      this.setState({
        reportTime: time,
        showReportTimePicker: false,
      });
    } else if (showRequireTimePicker) {
      this.setState({
        reqiureTime: time,
        showRequireTimePicker: false,
      });
    }
  };

  handleSelectArea = ({ name, pickType, id }) => {
    this.setState({
      [pickType]: name
    })
    // 切换国家，清空省市区
    switch (pickType) {
      case 'country':
        if(name !== this.state.country) {
          this.refs.provinceSelect.clear();
          this.refs.citySelect.clear();
          this.refs.countySelect.clear();
          this.setState({
            province: '',
            city: '',
            county: ''
          })
          this.refs.provinceSelect.pid = id;
        }
        break;
      case 'province':
        if(name !== this.state.province) {
          this.refs.citySelect.clear();
          this.refs.countySelect.clear();
          this.setState({
            city: '',
            county: ''
          })
          this.refs.citySelect.pid = id;
        }
        break;
      case 'city':
        if(name !== this.state.city) {
          this.refs.countySelect.clear();
          this.setState({
            county: ''
          })
          this.refs.countySelect.pid = id;
        }
        break;
    }
  }

  render() {
    const {
      customer,
      faultDevices,
      photos,
      reportTime,
      reqiureTime,
      showRequireTimePicker,
      showReportTimePicker
    } = this.state;
    return (
      <SafeAreaView style={{flex: 1}}>
        <StatusBar barStyle="light-content" backgroundColor="#5096fc" />
        <KeyboardAvoidingView
          behavior={Platform.OS == 'ios' ? 'padding' : 'height'}
          style={{flex: 1}}
          keyboardVerticalOffset={50}>
          <ScrollView style={{flex: 1}} keyboardDismissMode="on-drag">
            <ListItem
              bottomDivider
              onPress={() => {
                this.setState({showReportTimePicker: true});
              }}>
              <ListItem.Content>
                <ListItem.Title>报修时间</ListItem.Title>
                <View style={styles.subtitleView}>
                  <Text style={!reportTime && styles.colorGray}>{reportTime || '请选择报修时间'}</Text>
                </View>
              </ListItem.Content>
            </ListItem>
            <ListItem
              bottomDivider
              onPress={() => {
                Actions.customerSelector();
              }}>
              <ListItem.Content>
                <ListItem.Title>客户名称</ListItem.Title>
                <View style={styles.subtitleView}>
                  <Text style={!customer.customerName && styles.colorGray}>{customer.customerName || '请选择客户'}</Text>
                </View>
              </ListItem.Content>
            </ListItem>
            <ListItem bottomDivider>
              <ListItem.Content>
                <ListItem.Title>报修设备</ListItem.Title>
                <View style={styles.tagInputContaner}>
                  {Object.values(faultDevices).map((item, idx) => (
                    <TouchableOpacity
                      key={String(item.id)}
                      style={styles.tagContaner}
                      onPress={() => {
                        // 点击删除
                        const {faultDevices} = this.state;
                        delete faultDevices[item.eqptcode];
                        this.setState({faultDevices});
                      }}>
                      <Text style={styles.tag}>{item.eqptname}</Text>
                    </TouchableOpacity>
                  ))}
                  <Button
                    buttonStyle={styles.tagButton}
                    type="outline"
                    icon={{
                      name: 'add',
                      type: 'font-aswsome-5',
                      color: '#2089dc',
                    }}
                    onPress={() => {
                      Actions.equipmentSelector({
                        code: '%',
                        customerId: this.state.customer.id,
                        selected: this.state.faultDevices,
                      });
                    }}
                  />
                </View>
              </ListItem.Content>
            </ListItem>
            <ListItem
              bottomDivider
              onPress={() => {
                this.setState({showRequireTimePicker: true});
              }}>
              <ListItem.Content>
                <ListItem.Title>要求到场时间</ListItem.Title>
                <View style={styles.subtitleView}>
                  <Text style={!reqiureTime && styles.colorGray}>{reqiureTime || '请选择要求到场时间'}</Text>
                </View>
              </ListItem.Content>
            </ListItem>
            <ListItem bottomDivider>
              <ListItem.Content>
                <ListItem.Title>报修地区</ListItem.Title>
                <View style={styles.areaView}>
                  <AreaSelect pickType="country" onChange={this.handleSelectArea} />
                  <AreaSelect pickType="province" ref="provinceSelect" onChange={this.handleSelectArea} />
                  <AreaSelect pickType="city" ref="citySelect" onChange={this.handleSelectArea} />
                  <AreaSelect pickType="county" ref="countySelect" onChange={this.handleSelectArea} />
                </View>
              </ListItem.Content>
            </ListItem>
            <ListEditItem
              label="报修地址"
              placeholder="请输入报修地址"
              required
              ref="address"
              onChangeText={text => {
                const {customer} = this.state;
                customer.address = text;
                this.setState({customer});
              }}
              value={customer.address}
            />
            <ListEditItem
              label="故障描述"
              placeholder="请输入故障描述"
              ref="faultDesc"
              onChangeText={text => {
                this.setState({faultDesc: text});
              }}
              multiline
            />
            <ListItem bottomDivider>
              <ListItem.Content>
                <ListItem.Title>故障图片</ListItem.Title>
                <View style={styles.subtitleView}>
                  <View style={styles.photos}>
                    {photos.map((l, i) => {
                      return (
                        <TouchableOpacity
                          key={i}
                          onPress={() => {
                            let {photos} = this.state;
                            photos.splice(i, 1);
                            this.setState({photos});
                          }}>
                          <Image
                            style={styles.selector}
                            source={Api.photo(l)}
                          />
                        </TouchableOpacity>
                      );
                    })}
                    <Button
                      title="+"
                      onPress={this.chooseImage}
                      type="outline"
                      containerStyle={styles.selector}
                      buttonStyle={styles.button}
                      titleStyle={styles.selectorTitle}
                    />
                  </View>
                </View>
              </ListItem.Content>
            </ListItem>
            <ListEditItem
              label="联系人"
              placeholder="请输入联系人"
              onChangeText={text => {
                this.setState({linker: text});
              }}
            />
            <ListEditItem
              label="联系电话"
              placeholder="请输入联系电话"
              maxLength={11}
              keyboardType="numeric"
              onChangeText={text => {
                this.setState({cellphone: text});
              }}
            />
            <ListEditItem
              label="备注"
              placeholder="请输入备注"
              onChangeText={text => {
                this.setState({notes: text});
              }}
            />
            <DateTimePicker
              cancelTextIOS="取消"
              confirmTextIOS="确定"
              headerTextIOS="请选择日期"
              locale="zh_CN"
              isVisible={showRequireTimePicker || showReportTimePicker}
              mode={'datetime'}
              onConfirm={this.handleChooseDate} //确定按钮事件
              onCancel={() => {
                this.setState({
                  showRequireTimePicker: false,
                  showReportTimePicker: false
                })
              }} // 取消按钮事件
            />
          </ScrollView>
          <View style={styles.submitBot}>
            <Button
              title="提交"
              buttonStyle={{backgroundColor: '#5096fc', height: 50}}
              onPress={this.handleSubmit}
            />
          </View>
        </KeyboardAvoidingView>
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  selector: {
    width: 100,
    height: 100,
    margin: 10,
  },
  button: {
    width: 100,
    height: 100,
  },
  selectorTitle: {
    fontSize: 60,
    padding: 0,
    margin: 0,
    fontWeight: '100',
  },
  photos: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    margin: -10,
  },
  label: {
    fontSize: 16,
    color: '#86939e',
    fontWeight: 'bold',
  },
  errorMessage: {
    fontSize: 12,
    color: 'red',
    marginLeft: 0,
  },
  input: {
    flex: 1,
    fontSize: 18,
    marginVertical: 5,
    minWidth: 40,
  },
  inputPlaceholder: {
    color: '#CCC',
  },
  tagInputContaner: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'flex-start',
    marginVertical: 10,
  },
  tagContaner: {
    justifyContent: 'center',
    marginBottom: 10,
    marginRight: 10,
    padding: 10,
    borderRadius: 2,
    backgroundColor: '#dddddd',
  },
  tag: {
    color: '#777777',
    padding: 0,
    margin: 0,
    fontSize: 18,
  },
  tagButton: {
    paddingHorizontal: 10,
    width: 60,
  },
  subtitleView: {
    paddingTop: 10,
  },
  submitBot: {
    paddingHorizontal: 20,
    paddingVertical: 8,
  },
  colorGray: {
    color: '#b2b2b2'
  },
  areaView: {
    alignItems: 'center',
    justifyContent: 'space-between',
    flexDirection: 'row',
    width: '100%',
    marginTop: 12
  }
});
